package com.lss.loginregister.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Patterns;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.lss.loginregister.R;
import com.lss.loginregister.util.DatabaseHelper;
import com.lss.loginregister.util.PrefsUtil;

public class RegisterActivity extends AppCompatActivity {

    private DatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_register);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 初始化数据库工具类
        dbHelper = new DatabaseHelper(this);

        // 获取输入框
        TextInputEditText usernameInput = findViewById(R.id.tied_register_user);
        TextInputEditText passwordInput = findViewById(R.id.tied_register_pwd);
        TextInputEditText recheckPasswordInput = findViewById(R.id.tied_register_pwd_reCheck);
        TextInputEditText phoneInput = findViewById(R.id.tied_register_phone);
        TextInputEditText emailInput = findViewById(R.id.tied_register_mail);

        // 密码可见性切换逻辑
        TextInputLayout passwordLayout = findViewById(R.id.text_input_layout_password);
        passwordLayout.setEndIconOnClickListener(v -> {
            TextInputEditText passwordField = findViewById(R.id.tied_register_pwd);
            if (passwordField.getTransformationMethod() instanceof PasswordTransformationMethod) {
                passwordField.setTransformationMethod(null);
            } else {
                passwordField.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            passwordField.setSelection(passwordField.getText().length());
        });

        // 确认密码可见性切换逻辑
        TextInputLayout confirmPasswordLayout = findViewById(R.id.text_input_layout_confirm_password);
        confirmPasswordLayout.setEndIconOnClickListener(v -> {
            TextInputEditText confirmField = findViewById(R.id.tied_register_pwd_reCheck);
            if (confirmField.getTransformationMethod() instanceof PasswordTransformationMethod) {
                confirmField.setTransformationMethod(null);
            } else {
                confirmField.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            confirmField.setSelection(confirmField.getText().length());
        });

        // 注册按钮点击事件
        findViewById(R.id.btn_register).setOnClickListener(v -> {
            String username = usernameInput.getText().toString().trim();
            String password = passwordInput.getText().toString().trim();
            String recheckPassword = recheckPasswordInput.getText().toString().trim();
            String phone = phoneInput.getText().toString().trim();
            String email = emailInput.getText().toString().trim();

            // 基础验证（用户名和密码为必填项）
            if (username.isEmpty() || password.isEmpty() || recheckPassword.isEmpty()) {
                Toast.makeText(this, "请填写用户名和密码！", Toast.LENGTH_SHORT).show();
                return;
            }

            if (!password.equals(recheckPassword)) {
                Toast.makeText(this, "两次输入的密码不一致！", Toast.LENGTH_SHORT).show();
                return;
            }

            // 密码强度验证
            if (!isPasswordStrong(password)) {
                Toast.makeText(this, "密码需包含大小写字母和数字，且长度至少8位", Toast.LENGTH_SHORT).show();
                return;
            }

            // 手机号验证（可选，但填写时必须有效）
            if (!TextUtils.isEmpty(phone) && !isValidPhone(phone)) {
                Toast.makeText(this, "请输入有效的手机号", Toast.LENGTH_SHORT).show();
                return;
            }

            // 邮箱验证（可选，但填写时必须有效）
            if (!TextUtils.isEmpty(email) && !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                Toast.makeText(this, "请输入有效的邮箱地址", Toast.LENGTH_SHORT).show();
                return;
            }

            // 检查用户名是否已存在
            if (dbHelper.getUserByUsername(username) != null) {
                Toast.makeText(this, "用户名已存在！", Toast.LENGTH_SHORT).show();
                return;
            }

            // 插入数据到数据库
            long result = dbHelper.insertUser(username, password, phone, email);

            if (result != -1) {
                Toast.makeText(this, "注册成功！", Toast.LENGTH_SHORT).show();
                PrefsUtil.updateLoginTime(this);
                finish(); // 关闭当前界面
            } else {
                Toast.makeText(this, "注册失败，请重试！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 密码强度验证（需包含大小写字母和数字）
    private boolean isPasswordStrong(String password) {
        return password.length() >= 8 &&
                password.matches(".*[A-Z].*") &&
                password.matches(".*[a-z].*") && // 确保包含小写字母
                password.matches(".*[0-9].*");
    }

    // 手机号验证（更精确的正则表达式）[1,3](@ref)
    private boolean isValidPhone(String phone) {
        // 匹配国内主流运营商号段
        String regex = "^(1[3-9]\\d{9}$)";
        return phone.matches(regex);
    }
}